define(function(require,exports,module){
	require("resource/js/easyui/themes/icon.css");
	require("resource/js/easyui/easyloader.js");
	require("resource/js/component/rules.js");
	var ajax = require("resource/js/component/ajax.js");
	var alerts = require("resource/js/component/alerts.js");
	var easyutil = require("resource/js/component/easyutil.js");
	
	var config = {
			column:[[
		         {field:'contactsId',title:'contactsId',width:70,align:'center',height:50,hidden:true},
		         {field:'contactsName',title:'姓名',width:100,align:'center',height:50},
		         {field:'contactsMail',title:'邮件地址',width:200,align:'center',height:50},
		         {field:'groupName',title:'所在分组',width:120,align:'center',height:50},
		         {field:'contactsPhone',title:'手机号',width:120,align:'center',height:50},
		         {field:'contactsCompany',title:'公司',width:120,align:'center',height:50},
		         {field:'contactsDes',title:'描述',width:120,align:'center',height:50}
			]]
		};
	var dgutil = undefined;
	var datagridconfig = undefined;
	function initPage() {
		ajax.init().success(function(code,msg,data){
			if(code==0){
				dgutil = new easyutil.ajaxDataGrid(datagridconfig);
				initGroupList();
			} 
		}).error(function(code,msg,data) {
			$.messager.confirm('系统提示', msg, function(r){
	             if (r){
	            	 addEmail();
	             }
	        });
		}).post(BASEPATH + "/oa/email/checkUserMailExist.htm");
	}
	
	function addEmail(){
		$('#addEmaildlg').dialog({
			iconCls: 'icon-save',
			title:'添加邮箱账号',
			href: BASEPATH + '/view/oa/email/addEmail',
			onLoad: function() {
				$("#emailSuffix").text(emailSuffix);
			},
			buttons: [{
				text:'保存',
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#addEmailForm").form("validate")){
							//验证邮箱是否重复
							var email = $("#email").textbox("getValue");
							email += emailSuffix;
							ajax.init().success(function(code, msg, data){
								if (code == 0) {
									ajax.init().success(function(code, msg, data){
										if (code == 0) {
											dgutil = new easyutil.ajaxDataGrid(datagridconfig);
											initGroupList();
											$("#addEmaildlg").dialog("close");
											$.messager.show({
												title:'',
												msg: msg,
												timeout:1000,
												showType:'slide'
											});
										}
									}).error(function(code, msg, data){
										$.messager.show({
											title:'',
											msg: msg,
											timeout:1000,
											showType:'slide'
										});
									}).post(BASEPATH+'/oa/email/saveUserMail.htm', {email: email});
								}
							}).error(function(code, msg, data) {
								$.messager.show({
									title:'',
									msg: msg,
									timeout:1000,
									showType:'slide'
								});
							}).post(BASEPATH+'/oa/email/checkUserMailRepeat.htm', {email: email});
						}
					});
				}
			},{
				text:'取消',
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#addEmaildlg').dialog('close');
				}
			}]
		});
		$("#addEmaildlg").dialog("open");
	}
	
	//删除
	var delInit=function(baseUrl,rows){
		var checks="";
		for(var key in rows){
			if(key==rows.length-1){
				checks+=rows[key].contactsId;
			}else{
				checks+=rows[key].contactsId+",";
			}
		}
		easyutil.ajaxHandler(baseUrl,{contactsIds: checks},function(){
			dgutil.delRow(rows);
			initGroupList();
		});
	};
	//初始化分组下拉框
	function initCombobox(){ 
		ajax.init().success(function(code, msg, data){
			data.unshift({
				groupId:"", groupName:"请选择"
			});
			$("#groupId").combobox("loadData",data);
		}).post(BASEPATH+'/oa/emailContacts/getContactsGroupList.htm');
	};

	$("#adddlg").on('click', "#addGroup", function() { //新增联系人显示添加组
		$("#addGroupBlock").show();
		$("#addGroup").hide();
	}).on('click', '#cancelSaveGroup', function() { //新增联系人取消添加组
		$("#groupName").val('');
		$("#addGroupBlock").hide();
		$("#addGroup").show();
	}).on('click', '#saveGroup', function() { //新增联系人添加组
		var groupName = $("#groupName").val();
		if (groupName == null || groupName == '') {
			$.messager.show({
				title:'',
				msg: "组名不能为空",
				timeout:1000,
				showType:'slide'
			});
			return;
		}
		if (groupName.length > 100) {
			$.messager.show({
				title:'',
				msg: "组名长度必须介于0和100之间",
				timeout:1000,
				showType:'slide'
			});
			return;
		}
		ajax.init().success(function(code, msg, data){
			if (code == 0) {
				ajax.init().success(function(code, msg, data){
					if (code == 0) {
						initCombobox();
						$("#addGroupBlock").hide();
						$("#addGroup").show();
						$.messager.show({
							title:'',
							msg: msg,
							timeout:1000,
							showType:'slide'
						});
					}
				}).post(BASEPATH+'/oa/emailContacts/addContactsGroup.htm', {groupName: groupName});
			} else {
				$.messager.show({
					title:'',
					msg: msg,
					timeout:1000,
					showType:'slide'
				});
			}
		}).post(BASEPATH+'/oa/emailContacts/checkGroupName.htm', {groupName: groupName});
	});
	//初始化组列表
	function initGroupList() {
		ajax.init().success(function(code, msg, data){
			if (code == 0) {
				$("#groupTreeBody").html('');
				var treeHtml = '';
				if (data && data.length > 0) {
					treeHtml += '<li class="tree-item" data-group-id="">'
						+'<div><div class="tree-item-label">'
						+'<span class="tree-item-title">全部</span></div></div></li>';
					for (var i = 0; i < data.length; i++) {
						var operatorHtml = '';
						operatorHtml = '<span class="tree-update" data-group-id="'+data[i].groupId+'" data-group-name="'+data[i].groupName+'"></span>'
						+ '<span class="tree-del" data-group-id="'+data[i].groupId+'" data-group-person="'+data[i].personCount+'"></span>';
						treeHtml += '<li class="tree-item">'
							+ '<div><div class="tree-item-label" data-group-id="'+data[i].groupId+'">'
							+ '<span class="tree-item-title" title="'+data[i].groupName+'('+data[i].personCount+')">'+data[i].groupName+'('+data[i].personCount+')</span></div>'
							+ '<div class="tree-handle-block tree-hide">'
							+ operatorHtml
							+ '</span></div>'
							+ '</div></li>';
					}
				} else {
					treeHtml += '<li style="text-align: center; padding-top: 50px;">无数据</li>';
				}
				$("#groupTreeBody").append(treeHtml);
			}
		}).post(BASEPATH+'/oa/emailContacts/getContactsGroupTree.htm');
	}
	$("#groupTreeBody").on('click', '.tree-del', function() {
		var self = $(this);
		var groupId = self.data('group-id');
		var personCount = self.data('group-person');
		var confirmMsg = '确定要删除该组吗?';
		if (personCount > 0) {
			confirmMsg = '删除该组及组内联系人吗？';
		}
		$.messager.confirm('系统提示', confirmMsg, function(r){
             if (r){
            	 ajax.init().success(function(code, msg, data){
					if (code == 0) {
						initGroupList();
						dgutil.pager();
						$.messager.show({
							title:'',
							msg: msg,
							timeout:1000,
							showType:'slide'
						});
					}
				}).post(BASEPATH+'/oa/emailContacts/delContactsGroup.htm', {groupId: groupId});
             }
        });
		
	}).on('click', '.tree-update', function() {
		var self = $(this);
		var oldGroupName = self.data('group-name');
		$('#groupName').textbox('setValue', oldGroupName);
		$("#groupId").val(self.data('group-id'));
		$('#updateGroupdlg').dialog({
			title:'修改分组',
			buttons: [{
				text:'保存',
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#updateGroupform").form("validate")){
							var groupName = $('#groupName').textbox('getValue');
							if (oldGroupName == groupName) {
								updateContactsGroup();
							} else {
								ajax.init().success(function(code, msg, data){
									if (code == 0) {
										updateContactsGroup();
									} else {
										$.messager.show({
											title:'',
											msg: msg,
											timeout:1000,
											showType:'slide'
										});
									}
								}).post(BASEPATH+'/oa/emailContacts/checkGroupName.htm', {groupName: groupName});
							}
						}
					});
				}
			},{
				text:'取消',
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#updateGroupdlg').dialog('close');
				}
			}]
		});
		$("#updateGroupdlg").dialog("open");
	});
	
	function updateContactsGroup() {
		ajax.init().success(function(code, msg, data){
			if (code == 0) {
				initGroupList();
				dgutil.pager();
				$("#updateGroupdlg").dialog("close");
				$.messager.show({
					title:'',
					msg: msg,
					timeout:1000,
					showType:'slide'
				});
			}
		}).post(BASEPATH+'/oa/emailContacts/updateContactsGroup.htm', $("#updateGroupform").serializeJson());
	}
	
	//点击组列表查询
	$("#grouplist").on('click', '.tree-item-label', function() {
		$("#groupTreeBody").find('.group-tree-background-color').removeClass('group-tree-background-color');
		var self = $(this);
		self.parent().parent().addClass('group-tree-background-color');
		$("#searchGroup").val(self.data('group-id'));
		dgutil.pager(1);
	}).on('click', '#treeAddGroup', function() { //添加分组
		$('#addGroupdlg').dialog({
			title:'新增分组',
			buttons: [{
				text:'保存',
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#addGroupform").form("validate")){
							var groupName = $("#addGroupName").textbox("getValue");
							ajax.init().success(function(code, msg, data){
								if (code == 0) {
									ajax.init().success(function(code, msg, data){
										if (code == 0) {
											initGroupList();
											$("#addGroupName").textbox("setValue", "");
											$("#addGroupdlg").dialog("close");
											$.messager.show({
												title:'',
												msg: msg,
												timeout:1000,
												showType:'slide'
											});
										}
									}).post(BASEPATH+'/oa/emailContacts/addContactsGroup.htm', $("#addGroupform").serializeJson());
								} else {
									$.messager.show({
										title:'',
										msg: msg,
										timeout:1000,
										showType:'slide'
									});
								}
							}).post(BASEPATH+'/oa/emailContacts/checkGroupName.htm', {groupName: groupName});
						}
					});
				}
			},{
				text:'取消',
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#addGroupdlg').dialog('close');
				}
			}]
		});
		$("#addGroupdlg").dialog("open");
	});
	
	var addDialogInit = function(baseUrl){
		$("#adddlg").dialog({
			iconCls: 'icon-save',
			title:'新增联系人',
			href:baseUrl,
			onLoad:function(){
				using("combobox",function(){
					$("#groupId").combobox({
						valueField : 'groupId',
						textField: 'groupName',
						prompt: '请选择分组',
						editable: false,
						required: false
					});
					initCombobox();
				});
		    },
			buttons: [{
				text:'保存',
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#addform").form("validate")){
							//判断邮箱是否可用
							var contactsMail = $("#contactsMail").textbox("getValue");
							if ($("#groupId").combobox("getValue") == '') {
								$.messager.show({
									title:'',
									msg:"请选择分组",
									timeout:1000,
									showType:'slide'
								});
								return;
							}
							ajax.init().success(function(code, msg, data) {
								if (code == 0) {
									ajax.init().success(function(code,msg,data){
										dgutil.pager();
										initGroupList();
										$("#adddlg").dialog("close");
										alerts.show(msg);
									})
									.error(function(code,msg,data){
										alerts.alert(msg);
									}).post(BASEPATH+'/oa/emailContacts/addContacts.htm',$("#addform").serializeJson());
								} else {
									$.messager.show({
										title:'',
										msg:"邮箱已存在",
										timeout:1000,
										showType:'slide'
									});
								}
							}).post(BASEPATH+'/oa/emailContacts/checkContactsMail.htm', {contactsMail: contactsMail});
						}
					});
				}
			},{
				text:'取消',
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#adddlg').dialog('close');
				}
			}]
		});
		$("#adddlg").dialog("open");
	}
	
	function updateContacts() {
		ajax.init().success(function(code,msg,data){
			dgutil.pager();
			initGroupList();
			$("#adddlg").dialog("close");
			alerts.show(msg);
		})
		.error(function(code,msg,data){
			alerts.alert(msg);
		}).post(BASEPATH+'/oa/emailContacts/updateContacts.htm',$("#updform").serializeJson());
	}
	
	var updDialogInit = function(baseUrl,row){
		$("#adddlg").dialog({
			iconCls: 'icon-save',
			title: '修改',
			href:baseUrl,
			onLoad:function(){
				$("#contactsId").val(row.contactsId);
				using(["textbox","combobox"],function(){
					$("#groupId").combobox({
						valueField : 'groupId',
						textField: 'groupName',
						prompt: '请选择分组',
						editable: false,
						required: false
					});
					initCombobox();
					
					$("#contactsName").textbox("setValue",row.contactsName);
					$("#contactsMail").textbox("setValue",row.contactsMail);
					$("#groupId").combobox("setValue",row.groupId);
					$("#contactsPhone").textbox("setValue",row.contactsPhone);
					$("#contactsCompany").textbox("setValue",row.contactsCompany);
					$("#contactsDes").textbox("setValue",row.contactsDes);
					$("#oldContactsMail").val(row.contactsMail);
					
				});
		    },
			buttons: [{
				text:'保存',
				iconCls:'icon-ok',
				accessKey:{akey:18,mkey:83},
				handler:function(){
					using(["form"],function(){
						if($("#updform").form("validate")){
							//判断邮箱是否可用
							var contactsMail = $("#contactsMail").textbox("getValue");
							var oldContactsMail = $("#oldContactsMail").val();
							if ($("#groupId").combobox("getValue") == '') {
								$.messager.show({
									title:'',
									msg:"请选择分组",
									timeout:1000,
									showType:'slide'
								});
								return;
							}
							if (contactsMail != oldContactsMail) {
								ajax.init().success(function(code, msg, data) {
									if (code == 0) {
										updateContacts();
									} else {
										$.messager.show({
											title:'',
											msg:"邮箱已存在",
											timeout:1000,
											showType:'slide'
										});
									}
								}).post(BASEPATH+'/oa/emailContacts/checkContactsMail.htm', {contactsMail: contactsMail});
							} else {
								updateContacts();
							}
						}
					});
				}
			},{
				text:'取消',
				addClass:'l-btn-red',iconCls:'icon-not',
				accessKey:{akey:18,mkey:67},
				handler:function(){
					$('#adddlg').dialog('close');
				}
			}]
		});
		$("#adddlg").dialog("open");
	}

	module.exports = {
		init : function() {
			var buttons = {
				title: {
					_class: "",
					text: "收件列表"
				},
				btn: [
				{
					 iconCls: 'icon-search',
					 url:'/oa/emailContacts/getContactsPage.htm',
					 text:"查询",
					 addClass:'l-btn-display',
					 handler: function(){dgutil.pager(1);}
				},
				 {
					iconCls: "icon-add",
					text: "新增联系人",
					addClass: "l-btn-display",
					url: "/view/oa/email/contactsAdd",
					handler: addDialogInit
				},
				 {
					iconCls: 'icon-edit',
					url:'/view/oa/email/contactsUpdate',
					text:"修改",
					addClass:'l-btn-display',
					needRow:true,
					handler: updDialogInit
				},
				{
					iconCls: 'icon-remove',
					url:'/oa/emailContacts/delContacts.htm',
					text:"删除",
					addClass:'l-btn-display',
					needRows:true,
					isCheck:true,
					handler: delInit
				} ]
			};
			datagridconfig = {
				fitColumns: true,
				singleSelect: false,
				striped: true,
				autoRowHeight: false,
				fit: true,
				url: BASEPATH + '/oa/emailContacts/getContactsPage.htm',
				toolbar: buttons,
				columns: config.column,
				eid: "dg",
				args:"searchform",
				onClickRow:function(index,row){
				}
			};
			using(["parser","datagrid"], function() {//
				initPage();
			});
		}
	}
});
